import React, {useEffect, useRef, useState} from 'react';
import {Button, Checkbox, Form, Input, message, Modal, Radio} from "antd";
import styles from '../css/LoginForm.module.css'
import {addUser, getCaptcha, userLogin} from "../api/user";
import {useDispatch} from "react-redux";
import {changeLoginStatus, setUserInfo} from "../store/modules/userStore";

function LoginForm(props) {

    const [value, setValue] = useState('login')
    const loginFormRef = useRef()
    const registerFormRef = useRef()
    const [captcha, setCaptcha] = useState(null)
    const dispatch = useDispatch()
    // 登录表单的状态数据
    const [loginInfo, setLoginInfo] = useState({
        loginId: '',
        loginPwd: '',
        captcha: '',
        remember: false
    })
    const [registerInfo, setRegisterInfo] = useState({
        loginId: '',
        nickname: '',
        captcha: ''
    })
    useEffect(() => {
        handleCaptchaClick()
    }, [props.isShow]);
    // 注册表单的状态数据
    const handleOk = () => {
        props.closeModal()
    }

    const onChange = (e) => {
        setValue(e.target.value)
    }

    let content = null


    const updateInfo = (oldLoginInfo, value, key, setInfo) => {
        // setLoginInfo({
        //     ...loginInfo,
        //     key: value
        // })
        const obj = {...oldLoginInfo}
        obj[key] = value
        setInfo(obj)
        // console.log(loginInfo)
    }
    const handleCaptchaClick = async () => {
        const result = await getCaptcha()
        setCaptcha(result.data.data.code)
    }
    const handleCancel = () => {
        setRegisterInfo({
            loginId: '',
            nickname: "",
            captcha: ''
        })
        setLoginInfo({
            loginId: '',
            nickname: "",
            captcha: '',
            remember: false
        })
        props.closeModal()
    }
    const handleRegister = async () => {
        const res = await addUser(registerInfo);
        if (res.data.data) {
            message.success(res.data.message + '！默认密码为 123456')
            dispatch(setUserInfo(res.data.data))
            dispatch(changeLoginStatus(true))
            // 关闭弹窗
            handleCancel()
        } else {
            message.error(res.data.message)
            await handleCaptchaClick()
        }
    }

    const handleLogin = async () => {
        const res = await userLogin(loginInfo)
        if (!res.data.data.enabled) {
            message.error('账号被冻结，请联系管理员')
            await handleCaptchaClick()
        } else if (res.data.data.enabled) {
            message.success('登录成功')
            localStorage.setItem('userToken', res.data.data.token)
            dispatch(setUserInfo(loginInfo))
            dispatch(changeLoginStatus(true))
            props.closeModal()
        } else {
            message.error('登录失败')
            await handleCaptchaClick()
        }
    };

    const onRegisterChange = (changedValues, allValues) => {
        console.log(changedValues, allValues)
    }
    if (value === 'login') {
        // 登录
        content = (
            <Form
                labelCol={{
                    span: 8,
                }}
                wrapperCol={{
                    span: 16,
                }}
                style={{
                    maxWidth: 600,
                }}
                onFinish={handleLogin}
                ref={loginFormRef}
                autoComplete="off"
            >
                <Form.Item
                    label="账号"
                    name="loginId"
                    rules={[
                        {
                            required: true,
                            message: '请输入账号',
                        },
                    ]}
                >
                    <Input
                        placeholder="请输入你的登录账号"
                        value={loginInfo.loginId}
                        onChange={e => updateInfo(loginInfo, e.target.value, 'loginId', setLoginInfo)}
                    />
                </Form.Item>

                <Form.Item
                    label="密码"
                    name="loginPwd"
                    rules={[
                        {
                            required: true,
                            message: '请输入你的密码，新用户密码默认为123456',
                        },
                    ]}
                >
                    <Input.Password
                        placeholder="请输入你的密码"
                        value={loginInfo.loginPwd}
                        autoComplete="off"
                        onChange={e => updateInfo(loginInfo, e.target.value, 'loginPwd', setLoginInfo)}
                    />
                </Form.Item>

                <Form.Item
                    label="验证码"
                    name="captcha"
                    rules={[
                        {
                            required: true,
                            message: '请输入你的验证码',
                        },
                    ]}
                >
                    <div className={styles.captcha}>
                        <Input.Password
                            className={styles.captchaInput}
                            placeholder="请输入你的验证码"
                            value={loginInfo.captcha}
                            autoComplete="off"
                            onChange={e => updateInfo(loginInfo, e.target.value, 'captcha', setLoginInfo)}
                        />
                        <div
                            className={styles.captchaSvg}
                            onClick={handleCaptchaClick} dangerouslySetInnerHTML={{__html: captcha}}>
                        </div>
                    </div>
                </Form.Item>

                <Form.Item
                    name="remember"
                    wrapperCol={{
                        offset: 5,
                        span: 16,
                    }}
                    initialValue={loginInfo.remember}
                    valuePropName="checked"
                >
                    <Checkbox
                        style={{marginLeft: 60}}
                        onChange={e => updateInfo(loginInfo, e.target.value, 'remember', setLoginInfo)}
                        checked={loginInfo.remember}
                    >记住我</Checkbox>
                </Form.Item>

                <Form.Item
                    wrapperCol={{
                        offset: 5,
                        span: 16,
                    }}
                >
                    <Button
                        type="primary"
                        htmlType="submit"
                        style={{marginRight: 40, marginLeft: 40}}>登录</Button>
                    <Button type="primary" htmlType="submit">重置</Button>
                </Form.Item>
            </Form>
        )
    } else {
        // 注册
        content = (
            <Form
                labelCol={{
                    span: 8,
                }}
                wrapperCol={{
                    span: 16,
                }}
                style={{
                    maxWidth: 600,
                }}
                onFinish={handleRegister}
                ref={registerFormRef}
                autoComplete="off"
                onValuesChange={onRegisterChange}
            >
                <Form.Item
                    label="账号"
                    name="loginId"
                    rules={[
                        {
                            required: true,
                            message: '请输入账号',
                        }
                    ]}
                    validateTrigger="onBlur"
                >
                    <Input
                        placeholder="请输入你的登录账号"
                        value={registerInfo.loginId}
                        onChange={e => updateInfo(registerInfo, e.target.value, 'loginId', setRegisterInfo)}
                    />
                </Form.Item>

                <Form.Item
                    label="昵称"
                    name="nickname"
                    rules={[
                        {
                            required: true,
                            message: '请输入昵称',
                        },
                    ]}
                >
                    <Input
                        placeholder="请输入你的昵称"
                        value={registerInfo.nickname}
                        onChange={e => updateInfo(registerInfo, e.target.value, 'nickname', setRegisterInfo)}
                    />
                </Form.Item>

                <Form.Item
                    label="验证码"
                    name="captcha"
                    rules={[
                        {
                            required: true,
                            message: '请输入你的验证码',
                        },
                    ]}
                >
                    <div className={styles.captcha}>
                        <Input.Password
                            className={styles.captchaInput}
                            placeholder="请输入你的验证码"
                            value={registerInfo.captcha}
                            onChange={e => updateInfo(registerInfo, e.target.value, 'captcha', setRegisterInfo)}
                        />
                        <div
                            onClick={handleCaptchaClick} dangerouslySetInnerHTML={{__html: captcha}}>
                        </div>
                    </div>
                </Form.Item>

                <Form.Item
                    wrapperCol={{
                        offset: 5,
                        span: 16,
                    }}
                >
                    <Button
                        type="primary"
                        htmlType="submit"
                        style={{marginRight: 40, marginLeft: 40}}>注册</Button>
                    <Button type="primary" htmlType="submit">重置</Button>
                </Form.Item>
            </Form>
        )
    }

    return (
        <div>
            <Modal title="登录/注册" open={props.isShow} onOk={handleOk} onCancel={props.closeModal} footer={[]}>
                <Radio.Group value={value} onChange={onChange} defaultValue="login" buttonStyle="solid"
                             className={styles.group}>
                    <Radio.Button value="login" className={styles.button}>登录</Radio.Button>
                    <Radio.Button value="register" className={styles.button}>注册</Radio.Button>
                </Radio.Group>
                {content}
            </Modal>
        </div>
    );
}

export default LoginForm;